import React from 'react';
import  {render} from 'react-dom';

import firebase from "firebase";

import App from './App';
import * as serviceWorker from './serviceWorker';
import './styles/styles.scss'

import * as API from './shared/http';
import {history} from "./history";

import Route from './components/router/Route';
import Router from './components/router/Router';
import Home from "./pages/home";
import NotFount from "./pages/404";
import {Login} from "./pages/login";
import {SinglePost} from "./pages/post";
import {getFirebaseToken} from "./backend/auth";

export const renderApp = (state , callback = () => {}) => {
  render(
      <Router {...state}>
        <Route path="" component={App}>
          <Route path="/" component={Home} />
          <Route path="/login" component={Login} />
          <Route path="/posts/:postId" component={SinglePost} />
          <Route path="*" component={NotFount} />
        </Route>
      </Router>,
      document.getElementById('root'),
      callback
  )
}

let state = {
  location: window.location.pathname,
  user: {
    authenticated: false, // 已认证：默认没有认证
    profilePicture: null, // 个人认证图片
    id: null, // userId
    name: null, // 用户名
  },
  token: null, // token
}
renderApp(state);

history.listen(to => {
  const user = firebase.auth().currentUser;
  state = Object.assign({},state,{
    location: user ? to.location.pathname : '/login'
  });
  renderApp(state);
})

firebase.auth().onAuthStateChanged(async user => {
  if (!user){ // 身份认证更改的话，不存在用户则直接到 /login
    state = {
      location: state.location,
      user: {
        authenticated: false,
      }
    };
    return renderApp(state, () => {
      history.push('/login')
    });
  }


  // 存在用户
  const token = await getFirebaseToken();
  const res = await API.loadUser(user.uid);
  let renderUser;
  if (res.status === 404){
    const userPayload = {
      name: user.displayName,
      profilePicture: user.photoURL,
      id: user.uid
    };
    renderUser = await API.createUser(userPayload).then(res => res.json());
  }else{
    renderUser = await res.json();
  }

  // history.push('/'); // 这里不直接定向到主页去。毕竟有可能访问 login
  state =  Object.assign({} , state , {
    user: {
      name: renderUser.name,
      id: renderUser.id,
      profilePicture: renderUser.profilePicture,
      authenticated: true,
    },
    token
  });
  renderApp(state);
})

// ReactDOM.render(
//   <React.StrictMode>
//     <App />
//   </React.StrictMode>,
//   document.getElementById('root')
// );

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
